package com.flyee.utils
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.controls.SWFLoader;
	import mx.core.UITextField;
	
	public class GCHleper
	{
		public function GCHleper(){}
		
		public static function clearHandler(event:Event):void
		{
			var con:DisplayObjectContainer = event.currentTarget as DisplayObjectContainer;
			if(con == null) return;
			con.removeEventListener(Event.REMOVED_FROM_STAGE,clearHandler);
			clearChildren(con);
			beginGC();
		}
		
		public static function clearAll(container:DisplayObjectContainer):void{
			if(!container) return;
			clearChildren(container);
			beginGC();
		}
		
		/**
		 *强制垃圾回收 
		 * @return 
		 * 
		 */		
		public static function beginGC():void
		{
			try
			{
        		var tempGC:LocalConnection = new LocalConnection();
        		tempGC.connect("MoonSpirit");
        		var tempGC2:LocalConnection = new LocalConnection();
        		tempGC2.connect("MoonSpirit");
        		tempGC2.close();
			}
			catch(error : Error)
			{

			}
		}
				
		private static function clearChildren(con:DisplayObjectContainer):void
		{
			if(con is MovieClip || con is Sprite || con is Shape)
			{
				var tempDis:Object = con;
				tempDis.graphics.clear();
			}
			if(con is Loader)
			{
				Loader(con).unload();
			}
			while(con.numChildren > 0)
			{
				var child:DisplayObject = con.getChildAt(0);
				con.removeChildAt(0);
				if(child is DisplayObjectContainer)
				{
					var temp:*;
					if(child is SWFLoader)
					{
						temp = child as SWFLoader;
						temp.source = null;
						temp = null;
					}
					else if(child is Bitmap)
					{
						temp = child as Bitmap;
						if(temp.bitmapData != null) temp.bitmapData.dispose();
						temp = null;
					}
					else if(child is MovieClip)
					{
						temp = child as MovieClip;
						temp.stop();
						temp = null;
					}
					else if(child is Loader)
					{
						Loader(child).unload();
						child = null;
					}
					else if(child is UITextField){
						child = null;
					}
					else
					{
						temp = child as DisplayObjectContainer;
						if(temp.numChildren > 0) clearChildren(temp);
						temp = null;
					}
				}
				else
				{
					child = null;
				}
			}
		}
		
	}
}